// 
// Entify project
//  
// Author:
//       Lauri Taimila <lauri@taimila.com>
// 
// Copyright (c) 2010 Lauri Taimila
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;

namespace MonoDevelop.EntifyEditor
{
	/// <summary>
	/// Widget for editing relation details.
	/// </summary>
	public partial class RelationDetailsWidget : Gtk.Bin
	{
		/// <summary>
		/// Event indicates that property details has been changed from the editor.
		/// </summary>
		public delegate void RelationDetailsChanged();
    	public event RelationDetailsChanged DetailsChanged;

		/// <summary>
		/// Relation which details are modified with this widget.
		/// </summary>
		private Relation model;

		/// <summary>
		/// Model for relation type combobox. Contains all entities
		/// in the current entity set.
		/// </summary>
		private Gtk.ListStore relationTypeComboboxModel;

		/// <summary>
		/// List of entities. This is used for populating
		/// relation type combobox selection.
		/// </summary>
		private List<Entity> entities;

		/// <summary>
		/// Sets relation model to view and updates view
		/// to represent the current model.
		/// </summary>
		public Relation Model
		{
			set
			{
				this.model = value;
				this.UpdateView();
			}
		}

		/// <summary>
		/// Creates a new relation details widget.
		/// </summary>
		public RelationDetailsWidget()
		{
			this.Build();

			this.model = null;
			this.entities = new List<Entity>();

			// Set Entity renderer for relation type combobox selector.
			this.relationTypeComboboxModel = new Gtk.ListStore(typeof(Entity));
			Gtk.CellRendererText entityNameCell = new Gtk.CellRendererText();
			this.RelationTypeCombobox.PackStart(entityNameCell, true);
			this.RelationTypeCombobox.SetCellDataFunc(entityNameCell, new Gtk.CellLayoutDataFunc(this.RenderEntityName));
			this.RelationTypeCombobox.Model = this.relationTypeComboboxModel;

			this.UpdateView();
		}

		public void FocusToRelationNameEntry()
		{
			this.RelationNameEntry.HasFocus = true;
		}

		/// <summary>
		/// Redraw the relation type combobox.
		/// </summary>
		public void RefreshRelationTypeCombobox()
		{
			this.RelationTypeCombobox.QueueDraw();
		}

		/// <summary>
		/// Add entity to relation type combobox model.
		/// </summary>
		/// <param name="entity">
		/// Enity to add. <see cref="Entity"/>
		/// </param>
		public void AddEntityToRelationTypeCombobox(Entity entity)
		{
			this.entities.Add(entity);
			this.entities.Sort();
			this.UpdateRelationTypeCombobox();
		}

		/// <summary>
		/// Remove entity from relation type combobox model.
		/// </summary>
		/// <param name="entity">
		/// Enity to remove. <see cref="Entity"/>
		/// </param>
		public void RemoveEntityFromRelationTypeCombobox(Entity entity)
		{
			this.entities.Remove(entity);
			this.UpdateRelationTypeCombobox();
		}

		/// <summary>
		/// Updates UI components to represent values of the current model.
		/// </summary>
		private void UpdateView()
		{
			if(this.model == null)
			{
				this.RelationNameEntry.Text = "";
				this.ToManyRelationCheckbox.Active = false;
				this.RelationDescriptionEntry.Text = "";
				this.RelationDetails.Sensitive = false;
			}
			else
			{
				this.RelationNameEntry.Text = this.model.Name;
				this.ToManyRelationCheckbox.Active = this.model.ToMany;
				this.RelationDescriptionEntry.Text = this.model.Description;
				this.RelationDetails.Sensitive = true;
			}

			this.UpdateRelationTypeComboboxSelection();
		}

		/// <summary>
		/// Called when relation name has been changed. Updates the model.
		/// </summary>
		protected virtual void OnRelationNameEntryChanged (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.Name = this.RelationNameEntry.Text.Trim();
				this.model.PersistentName = this.model.Name;
				this.DetailsChanged();
			}
		}

		/// <summary>
		/// Called when 'To-Many relation' checkbox status has been changed. Updates the model.
		/// </summary>
		protected virtual void OnToManyRelationCheckboxToggled (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.ToMany = this.ToManyRelationCheckbox.Active;
				this.DetailsChanged();
			}
		}

		/// <summary>
		/// Called when relation type has been changed. Updates the model.
		/// </summary>
		protected virtual void OnRelationTypeComboboxChanged (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				Gtk.TreeIter iter;
				if(this.RelationTypeCombobox.GetActiveIter(out iter))
				{
					Entity selectedEntity = (Entity) this.relationTypeComboboxModel.GetValue(iter, 0);
					this.model.Type = selectedEntity.Id;
					this.DetailsChanged();
				}
			}
		}

		/// <summary>
		/// Called when relation description has been changed. Updates the model.
		/// </summary>
		protected virtual void OnRelationDescriptionEntryChanged (object sender, System.EventArgs e)
		{
			if(this.model != null)
			{
				this.model.Description = this.RelationDescriptionEntry.Text.Trim();
				this.DetailsChanged();
			}
		}

		/// <summary>
		/// Updates relation type combobox to contain all current entities and sets it selection
		/// to correct entity.
		/// </summary>
		private void UpdateRelationTypeCombobox()
		{
			// Update model to contain current values
			this.RelationTypeCombobox.Model = null;
			this.relationTypeComboboxModel.Clear();

			foreach(Entity entity in this.entities)
			{
				this.relationTypeComboboxModel.AppendValues(entity);
			}

			this.RelationTypeCombobox.Model = this.relationTypeComboboxModel;
			this.UpdateRelationTypeComboboxSelection();
		}

		/// <summary>
		/// Updates relation type combobox selection to correspond with the value in the model.
		/// </summary>
		private void UpdateRelationTypeComboboxSelection()
		{
			if(this.model != null && !string.IsNullOrEmpty(this.model.Type))
			{
				Gtk.TreeIter iter;
				this.relationTypeComboboxModel.GetIterFirst(out iter);
				bool notFound = true;

				while(notFound)
				{
					if(this.model.Type == (this.relationTypeComboboxModel.GetValue(iter, 0) as Entity).Id)
					{
						// Sets combobox value to correspond model value
						this.RelationTypeCombobox.SetActiveIter(iter);
						notFound = false;
					}
					else
					{
						if(!this.relationTypeComboboxModel.IterNext(ref iter))
						{
							// Model had value that cannot be used (entity has been removed since). Cleans selection.
							notFound = false;
							this.model.Type = null;
							this.RelationTypeCombobox.SetActiveIter(new Gtk.TreeIter());
						}
					}
				}
			}
			else
			{
				// Cleans combobox when details editor is insensitive
				this.RelationTypeCombobox.SetActiveIter(new Gtk.TreeIter());
			}
		}

		/// <summary>
		/// Rederer for relation type combobox.
		/// </summary>
		private void RenderEntityName(Gtk.CellLayout cellLayout, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			Entity entity = (Entity) this.relationTypeComboboxModel.GetValue(iter, 0);
			(cell as Gtk.CellRendererText).Text = entity.Name;
		}
	}
}
